package com.ktg.mes.pro.service.impl;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import com.ktg.common.core.domain.model.SqlResult;
import com.ktg.common.utils.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktg.common.utils.SecurityUtils;
import com.ktg.mes.unit.other.SQLListenerInterface;
import com.ktg.mes.unit.other.SQLListenerType;
import com.ktg.mes.wm.domain.WmIssueLine;
import com.ktg.mes.wm.domain.WmMaterialStock;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktg.mes.pro.mapper.ProItemNeedMapper;
import com.ktg.mes.pro.domain.ProItemNeed;
import com.ktg.mes.pro.service.IProItemNeedService;



/**
 * 客戶产品需求Service业务层处理
 *
 * @author byteco
 * @date 2022-12-12
 */
@Service
public class ProItemNeedServiceImpl extends ServiceImpl<ProItemNeedMapper, ProItemNeed> implements IProItemNeedService
{

    /**
     * 查询客戶产品需求
     *
     * @param entity 客戶产品需求
     * @param page 分页对象
     * @return 客戶产品需求
     */
    @Override
    public IPage<ProItemNeed> queryPageList(ProItemNeed entity, Page<ProItemNeed> page) {
        QueryWrapper<ProItemNeed> lqw = new QueryWrapper<ProItemNeed>(entity);
        lqw.orderByDesc("create_time");
        IPage<ProItemNeed> pageList = this.page(page, lqw);
        return pageList;
    }

    /**
     * 查询客戶产品需求
     *
     * @param entity 客戶产品需求
     * @return 客戶产品需求
     */
    @Override
    public List<ProItemNeed> queryList(ProItemNeed entity) {
        QueryWrapper<ProItemNeed> lqw = new QueryWrapper<ProItemNeed>(entity);
        lqw.orderByDesc("create_time");
        return this.list(lqw);
    }

    public ProItemNeed getInfo(Long id)
    {
        return this.getById(id);
    }


    /**
     * 新增客戶产品需求
     *
     * @param entity 客戶产品需求
     * @return 结果
     */
    @Override
    public void insert(ProItemNeed entity)
    {
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        this.save(entity);
    }

    /**
     * 修改客戶产品需求
     *
     * @param entity 客戶产品需求
     * @return 结果
     */
    @Override
    public boolean update(ProItemNeed entity)
    {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        return this.updateById(entity);
    }



    /**
     * 修改客备货戶产品需求
     *
     * @param entity 客戶产品需求
     * @return 结果
     */
    @Override
    public boolean updateStock(ProItemNeed entity)
    {
        entity.setStockUserId(String.valueOf(SecurityUtils.getUserId()));
        entity.setStockUserName(SecurityUtils.getUsername());
        entity.setStockDate(DateUtils.getNowDate());
        entity.setUpdateTime(DateUtils.getNowDate());
        return this.updateById(entity);
    }



    /**
     * 修改发货客戶产品需求
     *
     * @param entity 客戶产品需求
     * @return 结果
     */
    @Override
    public boolean updateShipped(ProItemNeed entity)
    {
        entity.setShippedUserId(String.valueOf(SecurityUtils.getUserId()));
        entity.setShippedUserName(SecurityUtils.getUsername());
        entity.setShippedDate(DateUtils.getNowDate());
        entity.setUpdateTime(DateUtils.getNowDate());
        return this.updateById(entity);
    }



    /**
     * 批量删除客戶产品需求
     *
     * @param recordIds 需要删除的客戶产品需求主键
     * @return 结果
     */
    @Override
    public boolean delete(Long[] recordIds)
    {

        return this.removeByIds(Arrays.asList(recordIds));
    }

    /**
     * 删除客戶产品需求信息
     *
     * @param recordId 客戶产品需求主键
     * @return 结果
     */
    @Override
    public boolean delete(Long recordId)
    {
        return this.removeById(recordId);
    }

    private LambdaQueryWrapper<ProItemNeed> buildQueryWrapper(ProItemNeed entity) {
        LambdaQueryWrapper<ProItemNeed> lqw = Wrappers.lambdaQuery();
                    lqw.eq(StringUtils.isNotBlank(entity.getCreateBy()), ProItemNeed::getCreateBy, entity.getCreateBy());
                    lqw.like(StringUtils.isNotBlank(entity.getClientName()), ProItemNeed::getClientName, entity.getClientName());
                    lqw.like(StringUtils.isNotBlank(entity.getItemName()), ProItemNeed::getItemName, entity.getItemName());
                    lqw.eq(StringUtils.isNotBlank(entity.getSpecification()), ProItemNeed::getSpecification, entity.getSpecification());
                    lqw.eq(StringUtils.isNotBlank(entity.getViscosity()), ProItemNeed::getViscosity, entity.getViscosity());
                    lqw.eq(StringUtils.isNotBlank(entity.getUnitOfMeasure()), ProItemNeed::getUnitOfMeasure, entity.getUnitOfMeasure());
                    lqw.eq(entity.getNeedDate() != null, ProItemNeed::getNeedDate, entity.getNeedDate());
                    lqw.eq(entity.getNeedCount() != null, ProItemNeed::getNeedCount, entity.getNeedCount());
                    lqw.eq(StringUtils.isNotBlank(entity.getNeedRemark()), ProItemNeed::getNeedRemark, entity.getNeedRemark());
                    lqw.eq(entity.getStockDate() != null, ProItemNeed::getStockDate, entity.getStockDate());
                    lqw.like(StringUtils.isNotBlank(entity.getStockUserName()), ProItemNeed::getStockUserName, entity.getStockUserName());
                    lqw.eq(entity.getStockCount() != null, ProItemNeed::getStockCount, entity.getStockCount());
                    lqw.eq(StringUtils.isNotBlank(entity.getStockReamrk()), ProItemNeed::getStockReamrk, entity.getStockReamrk());
                    lqw.eq(entity.getShippedType() != null, ProItemNeed::getShippedType, entity.getShippedType());
                    lqw.eq(entity.getShippedDate() != null, ProItemNeed::getShippedDate, entity.getShippedDate());
                    lqw.eq(StringUtils.isNotBlank(entity.getShippedRemark()), ProItemNeed::getShippedRemark, entity.getShippedRemark());
        return lqw;
    }

    /**
     * 删除 备货状态信息
     * @param recordId
     */
    public void deleteStockInfo(String recordId){
        getBaseMapper().deleteStockInfo(recordId);
    }


    //监听领料,出库
    @SQLListenerInterface(tableName = "wm_issue_line",listerType = {SQLListenerType.BeforeAll})
    public SqlResult wmIssueLineListener(SQLListenerType type, WmIssueLine oldObj, WmIssueLine newObj) {
        try {
            if (SQLListenerType.DeleteBefore == type){
                if (oldObj.getItemNeedId() == null || !oldObj.getOutType().equals("备货") || oldObj.getIsInStock().equals("0")){
                    return SqlResult.ok(null,null);
                }
            }else if (SQLListenerType.AddBefore == type){
                if (newObj.getItemNeedId() == null || !newObj.getOutType().equals("备货") || newObj.getIsInStock().equals("0")){
                    return SqlResult.ok(null,null);
                }
            }else if (SQLListenerType.ChangeBefore == type){
                if (newObj.getItemNeedId() == null && oldObj.getItemNeedId() == null){
                    return SqlResult.ok(null,null);
                }
                if (!oldObj.getOutType().equals("备货") && !newObj.getOutType().equals("备货")){
                    return SqlResult.ok(null,null);
                }
            }
            ProItemNeed proItemNeed = null;
            if (oldObj != null && newObj != null
                && oldObj.getOutType().equals("备货")
                && newObj.getOutType().equals("备货")
                && oldObj.getIsInStock().equals("1")
                && newObj.getIsInStock().equals("1")
//                && oldObj.getItemRecptLineId().equals(newObj.getItemRecptLineId())
                && oldObj.getItemNeedId().longValue() == newObj.getItemNeedId().longValue() ) {

                float newCount = newObj.getQuantity().floatValue();
                float oldCount = oldObj.getQuantity().floatValue();

                proItemNeed = getById(newObj.getItemNeedId());
                proItemNeed.setStockCount(BigDecimal.valueOf(proItemNeed.getStockCount().floatValue() - oldCount + newCount));
                updateById(proItemNeed);
            } else{
                if (oldObj != null && oldObj.getOutType().equals("备货") &&  oldObj.getIsInStock().equals("1")){
                    float oldCount = oldObj.getQuantity().floatValue();
                    proItemNeed = getById(oldObj.getItemNeedId());
                    proItemNeed.setStockCount(BigDecimal.valueOf(proItemNeed.getStockCount().floatValue() - oldCount));
                    proItemNeed.setShippedType(10L);
                    updateById(proItemNeed);
                }
                if (newObj != null && newObj.getOutType().equals("备货") && newObj.getIsInStock().equals("1")){
                    float newCount = newObj.getQuantity().floatValue();
                    proItemNeed = getById(newObj.getItemNeedId());
                    float aaa = 0;
                    if (proItemNeed.getStockCount() != null){
                        aaa = proItemNeed.getStockCount().floatValue();
                    }
                    proItemNeed.setStockCount(BigDecimal.valueOf(aaa + newCount));
                    if (proItemNeed.getStockCount().floatValue() > proItemNeed.getNeedCount().floatValue()){
                        return SqlResult.error("备货数量不能大于客户需求数量",proItemNeed);
                    }
                    if (proItemNeed.getStockCount().floatValue() == proItemNeed.getNeedCount().floatValue()){
                        proItemNeed.setShippedType(20L);
                    }else if (proItemNeed.getStockCount().floatValue() == proItemNeed.getNeedCount().floatValue()){
                        proItemNeed.setShippedType(10L);
                    }
                    updateById(proItemNeed);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return SqlResult.error(this.getClass().toString(),e);
        }
        return SqlResult.ok(null,null);
    }

}
